﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcFrontEnd.Models;
using FeedReader.Shared.Workers;
using FeedReader.Shared;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using FeedReader.Shared.Data;
using System.Web.Security;
using System.Xml.Linq;

namespace MvcFrontEnd.Controllers
{
    public class FeedController : Controller
    {
        static CloudStorageAccount acc = CloudStorageAccount.FromConfigurationSetting(""); //TODO: Fill in the config setting
        UsersDataSource usertable = new UsersDataSource(acc);
        UserSubscrptionsDataSource usersubstable = new UserSubscrptionsDataSource(acc);
        //
        // GET: /Feed/

        public ActionResult Index()
        {
            string id =User.Identity.Name;

            List<UserSubscrptionsDataModel> subs = usersubstable.Select(id).ToList<UserSubscrptionsDataModel>();
            FeedRepository myrepo = new FeedRepository();

            List<List<ViewPost>> usersubs = new List<List<ViewPost>>();
            foreach (UserSubscrptionsDataModel item in subs)
            {
                usersubs.Add(myrepo.getposts(item.BlogID));
            }
            return View(usersubs);
        }
        public ActionResult ViewFeed(string id)
        {
            //id is the blog id
            
            FeedRepository myrepo = new FeedRepository();
            ViewData["Title"] = myrepo.getFeedMeta(id).Title;
           List<ViewPost> items= myrepo.getposts(id);

            return View(items);
        }

        public ActionResult Upload()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFile()
        {
            //Models.TheUser user = TheUser.GetUser("id");

            String username = "0000"; //TODO: Change this
            CloudStorageAccount acc = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            CloudBlobClient theclient = acc.CreateCloudBlobClient();
            CloudBlobContainer thecontainer = theclient.GetContainerReference(ContainerNameServices.OPML);
            thecontainer.CreateIfNotExist();
            CloudBlob theblob = thecontainer.GetBlobReference(username);

            theblob.UploadFromStream(Request.Files["file1"].InputStream);

            CloudQueueClient queueclient = acc.CreateCloudQueueClient();

            CloudQueue queue = queueclient.GetQueueReference(QueueNameServices.OPMLQueue);
            queue.CreateIfNotExist();
            Utils.QueueXMLMessage message = new Utils.QueueXMLMessage();
            message.UserID = username;
            message.Reference = username;
            var xml = new XElement("Message",
                new XElement("Username", message.UserID),
                new XElement("blobref"), message.Reference);

            queue.AddMessage(new CloudQueueMessage(System.Text.Encoding.ASCII.GetBytes(xml.ToString()))); //need to pass userID as well as URL

            return RedirectToAction("Index", "Home");
        }
        public ActionResult StartPreview()
        {
            return View();
        }
        [HttpPost]
        public ActionResult StartPreview(FormCollection form)
        {
            FeedFetcher fetcher = new FeedFetcher();

            Feed Myfeed=fetcher.FetchFeed(form["url"]);

            ViewFeed model = new ViewFeed();
            model.Title = Myfeed.Title;
            model.url = Myfeed.URL;

            model.posts = (from d in Myfeed.Posts
                           select (new ViewPost()).ParsePostData(d, d.Content)).ToList<ViewPost>();
            return View("Preview",model);
        }
        [HttpPost]
        public ActionResult AcceptPreview(FormCollection form)
        {
            BlogIDDataSource blogid = new BlogIDDataSource(acc);
            string url = form["url"];

            CloudQueue thequeue = acc.CreateCloudQueueClient().GetQueueReference(QueueNameServices.RecieveQueue);
            Utils.QueueXMLMessage message = new Utils.QueueXMLMessage();
            message.Reference = url;
            message.UserID = User.Identity.Name.ToString();
            var xml = new XElement("Message",
                new XElement("Username",message.UserID),
                new XElement("URL"),message.Reference);
            
            thequeue.AddMessage(new CloudQueueMessage(System.Text.Encoding.ASCII.GetBytes(xml.ToString()))); //need to pass userID as well as URL
           

            //UserSubscrptionsDataModel newsub = new UserSubscrptionsDataModel(); // adding the new subscription should be done in the backend. 
            //newsub.BlogID = BlobNameServices.CreateBlobEntry(url, blogid);      // however could thi simpact performance? IE - laging?
            //newsub.UserID = User.Identity.Name.ToString();
            //usersubstable.Insert(newsub);
            return View("Index");
        }

        public ActionResult ViewAllFeeds()
        {
            CloudBlobClient theclient = acc.CreateCloudBlobClient();

            FeedsDataSource feedtable = new FeedsDataSource(acc);

            var results = feedtable.Select();

            return View(results);

        }
    }
}
